How to use <semaphore> in C++20?

Below is the step-by-step tutorial on the use of semaphores in C++ programs.

STEP 1: Include the Header

To use semaphores in your C++ program, you need to include the <semaphore> header:

#include <semaphore>

STEP 2: Semaphore Basics

You can create a semaphore object like this:

std::counting_semaphore<size_t> sem(1); // Initialize a semaphore with an initial count of 1

std::counting_semaphore is a type of semaphore that allows a specified number of threads to access a resource concurrently. In this example, only one thread can access the resource protected by sem at a time.

STEP 3: Acquiring and Releasing

There are 3 methods to acquire and release a semaphore object:

Method 1: Aquire and Release

To acquire (lock) the semaphore, you can use the acquire method:

sem.acquire();
// Critical section code
sem.release();

The acquire method decreases the semaphore count by one, effectively locking it. The release method increases the count, releasing the semaphore.

Method 2: Try-Aquire

You can also use the try_acquire method to try to acquire the semaphore without blocking:

if (sem.try_acquire()) {
    // Successfully acquired the semaphore
    // Critical section code
    sem.release();
} else {
    // Semaphore was not acquired
}

Method 2: Waiting with Timeout

C++20 also introduced the try_acquire_for and try_acquire_until methods to try acquiring the semaphore with a timeout.

if (sem.try_acquire_for(std::chrono::seconds(1))) {
    // Successfully acquired the semaphore within 1 second
    // Critical section code
    sem.release();
} else {
    // Semaphore was not acquired within 1 second
}

C++ 20 – Header

The C++20 <semaphore> header is part of the Concurrency Library Technical Specification (TS). Semaphores are synchronization primitives that help control access to shared resources in multi-threaded programs. The <semaphore> header provides the standard C++ way to work with semaphores.

In this article, we have covered important sections of semaphore headers such as the main classes, and usage of semaphore headers in C++20 along with examples.

Similar Reads

How to use in C++20?

Below is the step-by-step tutorial on the use of semaphores in C++ programs....

Types of Semaphores

The header provides two types of semaphores that are:...

Advantages of Semaphores

...

Contact Us